defmodule IocpMonitor.Server do
  @moduledoc """
  接受电流盒子TCP连接的服务器。
  只负责接受连接，不负责TCP通信
  """

  require Logger

  use GenServer
  use IocpMonitor.Types

  @doc """
  启动进程服务器进程
  """
  @spec start_link(port()) :: {:ok, pid()} | {:error, term()}
  def start_link(port) do
    GenServer.start_link(__MODULE__, port, name: __MODULE__)
  end

  @impl true
  def init(port) do
    {:ok, tcp_server_socket} = :gen_tcp.listen(port, [
      :list,
      packet: :raw,
      active: false,
      reuseaddr: true,
      send_timeout: 5_000,
      send_timeout_close: true
    ])
    GenServer.cast(__MODULE__, :accept)
    {:ok, tcp_server_socket}
  end

  @impl true
  def handle_cast(:accept, tcp_server_socket) do
    {:ok, client} = :gen_tcp.accept(tcp_server_socket)
    IocpMonitor.Client.Supervisor.start_child(client)
    GenServer.cast(__MODULE__, :accept)
    {:noreply, tcp_server_socket}
  end

  @impl true
  def handle_info(message, tcp_server_socket) do
    Logger.warn(inspect(message))
    {:noreply, tcp_server_socket}
  end
end
